<!--
  - Copyright (c) 2019.  武汉中科图灵科技有限公司
  - Date :  2019/1/5
  - Author ：F12 Console=> atob("MzMxNDkxODAwQHFxLmNvbQ==")
  - Version ：1.6.2
  -->

<template>
  <div id="slmapmain">
    <!-- <div class="abstatic-height"></div> -->
    <div
      class="map-mode-pannel"
      :class="{ 'map-pannel-show': isSelectMode }"
      v-loading="mapLoad"
    >
      <el-amap
        vid="stree-light-amap"
        ref="map"
        resizeEnable="true"
        :plugin="plugin"
        :amap-manager="amapManager"
        :center="center"
        :zooms="zooms"
        :zoom="zoom"
        :events="events"
        class="mapset"
        :viewMode="vmode"
        :pitch="vrotate"
      >
        <el-amap-marker
          v-for="(marker, index) in markers"
          :key="marker.id"
          :position="marker.position"
          :vid="index"
          :id="marker.id"
          :events="marker.events"
        >
          <div class="map-marker-wrapn">
            <div
              class="main-map-markern"
              :class="{
                'main-map-marker__normaln': marker.status == '0',
                'main-map-marker__notify': marker.status == '1'
              }"
            >
              {{ marker.count }}
            </div>
            <p class="bubble">
              <i class="build-name">{{ marker.label }}</i>
              <i class="arrow-up"></i>
            </p>
          </div>
        </el-amap-marker>
        <el-amap-polyline
          v-for="(item, index) in polylineList"
          :key="index"
          :editable="false"
          lineJoin="round"
          strokeColor="#ff0000"
          strokeWeight="10"
          :path="item"
        ></el-amap-polyline>
      </el-amap>
    </div>
    <!-- 列表模式 -->
    <div
      class="list-mode-pannel"
      :class="{ 'list-pannel-show': !isSelectMode }"
    >
      <el-scrollbar style="height: 100%;">
        <mapListModel
          :loadData="!isSelectMode"
          :channelId.sync="channelId"
          @showSensor="showSensor"
        ></mapListModel>
      </el-scrollbar>
    </div>

    <div class="map-tool">
      <div class="map-tool__right" :class="{ toolspannel: isExpand }">
        <div class="map-tool-rightwrap">
          <title-warp title="设备实时状态" widthAuto style="overflow:hidden">
            <div class="border_message">
              <div class="border_message_num">
                <border-cont
                  :num="totalStatus.callCount"
                  :type="'报警'"
                  :color="'bottom,#FF6574,#FA4F6C,#F53563'"
                ></border-cont>
              </div>
              <div class="border_message_num">
                <border-cont
                  :num="totalStatus.callCount"
                  :type="'故障'"
                  :color="'bottom,#F8BA67,#E69E3F,#D58824'"
                ></border-cont>
              </div>
              <div style="margin-top: 10px;" class="border_message_num">
                <border-cont
                  :num="totalStatus.offCount"
                  :type="'离线'"
                  :color="'bottom,#87DCFE,#4EC6FE,#02A4F9'"
                ></border-cont>
              </div>
              <div style="margin-top: 10px;" class="border_message_num">
                <border-cont
                  :num="totalStatus.normalCount"
                  :type="'正常'"
                  :color="'bottom,#63FC92,#4AFBA5,#37FFB8'"
                ></border-cont>
              </div>
            </div>
          </title-warp>

          <div class="list-warp">
            <title-warp title="火警设备列表" widthAuto>
              <div style="padding: 10px; color: #fff">
                联网单位：
                <el-select
                  @change="unitChange"
                  v-model="curUnitId"
                  filterable
                  placeholder="请选择"
                >
                  <el-option
                    v-for="item in unitList"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  >
                  </el-option>
                </el-select>
              </div>

              <div class="untreated-list" style="height: 400px;overflow:auto;">
                <div
                  v-if="deviceList.length > 0"
                  style="height:100%"
                  v-loading="loading"
                >
                  <el-scrollbar style="height:100%">
                    <dl
                      class="untreated-list-item"
                      v-for="item in deviceList"
                      :key="item.id"
                    >
                      <dt style="cursor: pointer">
                        <i
                          ><icon-svg
                            icon-class="guanlian"
                            style="fill:#2bdef5"/></i
                        >火警设备{{ item.sensorNo }}
                      </dt>
                      <dd class="untreated-pain">
                        设备状态:{{ item.status }} | {{ item.updTime }}
                      </dd>
                      <dd class="untreated-pain">
                        设备位置:{{ item.positionDescription }}
                      </dd>
                      <dd>
                        <el-button
                          size="mini"
                          type="text"
                          @click="handleRows(item, 'show')"
                          ><i style="margin-right: 5px"
                            ><icon-svg
                              icon-class="ditumoshi"
                              style="fill:#2bdef5"/></i
                          >查看路线</el-button
                        >
                        <el-button
                          size="mini"
                          type="text"
                          @click="handleRows(item, 'set')"
                          ><i style="margin-right: 5px"
                            ><icon-svg
                              icon-class="setting"
                              style="fill:#2bdef5"/></i
                          >设置路线</el-button
                        >
                      </dd>
                    </dl>
                    <div
                      class="loadmore-btn-goto"
                      v-if="unhandleItems.length >= 20"
                    >
                      <el-button type="text" @click="checkMore"
                        >查看更多</el-button
                      >
                    </div>
                  </el-scrollbar>
                </div>
                <div v-else>
                  <p class="none-list">暂无火警设备</p>
                </div>
              </div>
            </title-warp>
          </div>
        </div>

        <!-- 顶部工具栏 -->
        <div class="tool-wrap" :class="{ 'map-width-select': !isSelectMode }">
          <border-warp style="padding: 5px 10px">
            <div class="tool-wrap-items">
              <div
                class="map-listchange__mode"
                :class="{ 'map-mode-select': isSelectMode }"
                @click="changeMode('map')"
              >
                地图模式
              </div>
              <div
                class="map-listchange__mode"
                :class="{ 'list-mode-select': !isSelectMode }"
                @click="changeMode('list')"
              >
                列表模式
              </div>
              <div
                @click="handleCommand('showtrafic')"
                class="map-tool-item"
                v-show="isSelectMode"
              >
                路况
              </div>
              <div
                @click="handleCommand('showpich')"
                class="map-tool-item"
                v-show="isSelectMode"
              >
                测距
              </div>
              <div class="map-dotshow-wrap" v-show="isSelectMode">
                <span>报警</span>
                <span>故障</span>
              </div>
              <div class="map-search" v-show="isSelectMode">
                <el-dropdown @command="selectHandle">
                  <span class="el-dropdown-link">
                    {{ droptext
                    }}<i class="el-icon-caret-bottom el-icon--right"></i>
                  </span>
                  <el-dropdown-menu slot="dropdown">
                    <el-dropdown-item command="1">建筑</el-dropdown-item>
                    <el-dropdown-item command="2">地名</el-dropdown-item>
                    <el-dropdown-item command="3" v-if="issuperadmin"
                      >站点</el-dropdown-item
                    >
                  </el-dropdown-menu>
                </el-dropdown>
                <el-autocomplete
                  v-show="localSearch == '1'"
                  class="search-select"
                  popper-class="propper-class"
                  v-model="selectBuildId"
                  :fetch-suggestions="querySearch"
                  placeholder="请输入建筑名"
                  @select="handleSelect"
                  clearable
                >
                </el-autocomplete>
                <el-select
                  style="width:220px"
                  v-show="localSearch == '2'"
                  v-model="searchAddressKw"
                  filterable
                  clearable
                  remote
                  reserve-keyword
                  placeholder="请输入地址"
                  :remote-method="remoteMethod"
                  @change="selectedAddress"
                  value-key="location"
                  :loading="loading"
                >
                  <el-option
                    v-for="(item, index) in searchAddressList"
                    :key="index"
                    :label="item.name"
                    :value="item"
                  >
                    <span>{{ item.name }}</span>
                    <span style="color: #999; font-size: 12px">{{
                      item.district
                    }}</span>
                  </el-option>
                </el-select>
                <el-autocomplete
                  v-show="localSearch == '3'"
                  class="search-select"
                  popper-class="tenant-propper-class"
                  v-model="selectTenant"
                  :fetch-suggestions="tenantSearch"
                  placeholder="请输入关键词"
                  @select="handleSelecttenant"
                >
                </el-autocomplete>
              </div>
              <div class="map-tool__left">
                <div
                  class="map-tool-sensors"
                  :class="{ toolsexpand: isExpand }"
                  @click="changeIt"
                >
                  <i class="class-icon-show">
                    <icon-svg icon-class="show" style="fill:#2bdef5" />
                  </i>
                  <i class="class-icon-hide">
                    <icon-svg icon-class="hide" style="fill:#2bdef5" />
                  </i>
                  报警列表
                </div>
              </div>
            </div>
          </border-warp>
        </div>
      </div>
    </div>

    <!-- 底部导航 -->
    <!-- <bottom-nav></bottom-nav> -->

    <planDialog
      :Show.sync="realtimePointShow"
      :buildId.sync="buildId"
      :channelId.sync="channelId"
    ></planDialog>
    <el-dialog
      title="处理提示"
      :visible.sync="isdelalram"
      :show-close="false"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      custom-class="xf-jc-dialog"
      width="360px"
      height="160px"
    >
      <div class="xf-jc-deletect">
        <el-radio-group v-model="switchalramtype" v-if="alarmtype == 1">
          <el-radio label="1">真实火警</el-radio>
          <el-radio label="2">火警测试</el-radio>
          <el-radio label="0">误报</el-radio>
        </el-radio-group>
        <p v-else>当前故障确认已处理吗？</p>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" size="mini" @click="handleSure(rowsId)"
          >确定</el-button
        >
        <el-button size="mini" type="text" @click="isdelalram = false"
          >取消</el-button
        >
      </div>
    </el-dialog>

    <!-- 路线配置 -->
    <el-dialog
      title="设置路线"
      :visible.sync="lineDialogVisible"
      :show-close="false"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      custom-class="xf-jc-dialog"
      width="900px"
    >
      <div class="add-line-top">
        <el-button type="primary" size="mini" @click="subMitLine"
          >保存</el-button
        >
        <el-button size="mini" @click="lineDialogVisible = false" type="text"
          >取消</el-button
        >
      </div>
      <div class="set-line-block">
        <div class="left-warp">
          <div class="line-title">
            路线列表
            <el-button
              type="success"
              style="float: right;margin-top: -5px"
              size="mini"
              @click="addLineItem()"
              >增加路线</el-button
            >
          </div>
          <border-warp widthAuto>
            <el-tree
              ref="lineTree"
              highlight-current
              icon-class="n"
              :data="treeData"
              node-key="lineName"
              :props="{
                children: 'children',
                label: 'lineName'
              }"
              @node-click="handleLineItem"
            >
              <span class="custom-tree-node" slot-scope="{ node, data }">
                <span>{{ node.label }}</span>
                <span>
                  <el-button
                    type="text"
                    icon="el-icon-edit"
                    @click.stop="editLineItem(data)"
                  ></el-button>
                  <el-button
                    type="text"
                    icon="el-icon-circle-close-outline"
                    @click.stop="deleteLineItem(data)"
                  ></el-button>
                </span>
              </span>
            </el-tree>
          </border-warp>
        </div>

        <div class="right-warp">
          <div class="line-title">
            路灯杆列表
            <el-button
              type="success"
              style="float: right;margin-top: -5px"
              size="mini"
              @click="setLineVisible = true"
              >选择路灯杆</el-button
            >
          </div>
          <border-warp widthAuto>
            <el-table :data="curLine.lines" style="width: 100%">
              <el-table-column type="index" label="排序" width="60" />
              <el-table-column
                prop="id"
                label="id"
                width="60"
              ></el-table-column>
              <el-table-column align="center" label="led屏编号">
                <template slot-scope="scope">
                  <span>{{ scope.row.terminalScreenNo }}</span>
                </template>
              </el-table-column>
              <!-- <el-table-column prop="online" label="在线状态">
                <template slot-scope="scope">
                  <span>{{ scope.row.online == 0 ? "离线" : "在线" }}</span>
                </template>
              </el-table-column> -->
              <el-table-column align="center" label="指示" width="200">
                <template slot-scope="scope">
                  <el-radio-group v-model="scope.row.indicationSign">
                    <el-radio :label="1">左</el-radio>
                    <el-radio :label="2">右</el-radio>
                    <el-radio :label="3">停</el-radio>
                  </el-radio-group>
                </template>
              </el-table-column>
              <el-table-column align="center" label="操作" width="130">
                <template slot-scope="scope">
                  <el-button
                    :disabled="scope.$index === 0"
                    type="text"
                    size="mini"
                    @click="moveUp(scope.row, scope.$index)"
                  >
                    上移
                  </el-button>
                  <el-button
                    :disabled="scope.$index === curStreeLightList.length - 1"
                    type="text"
                    size="mini"
                    @click="moveDown(scope.row, scope.$index)"
                  >
                    下移
                  </el-button>
                </template>
              </el-table-column>
            </el-table>
          </border-warp>
        </div>
      </div>

      <el-dialog
        width="550px"
        title="增加路灯杆"
        :visible.sync="setLineVisible"
        append-to-body
        @open="getStreeLightList"
        @close="setStreeLightList"
      >
        <el-transfer
          :titles="['所有路灯杆', '选中路灯杆']"
          v-model="selectStreeLightList"
          :data="streeLightList"
          :props="{ key: 'id', label: 'label' }"
        >
        </el-transfer>
      </el-dialog>
    </el-dialog>
  </div>
</template>

<script>
import clip from "@/utils/clipboard"; // use clipboard directly
import { mapGetters } from "vuex";
import planDialog from "./components/realtimePoints";
import mapListModel from "./components/mapListModel";
import BottomNav from "@/components/BottomNav";

import {
  getBuildingList,
  getAllStatus,
  getUnhandleList,
  changeRsolve,
  changeFireRsolve,
  getAllTenant,
  getTenantPos,
  getMaxAlarm
} from "@/api/datahandler/deviceAbnormal/index";

import { getDeviceAll } from "@/api/system/streeLight.js";

import {
  getFireDeviceByProject,
  getLinesByDeviceId,
  updateLineStreeLight
} from "@/api/system/streeLight.js";

import {
  getUnitAll //获取所有联网单位
} from "@/api/admin/network/index";

import { AMapManager } from "vue-amap";
// [114.42377, 30.50469]
let amapManager = new AMapManager();
let cluster;
export default {
  name: "streeLightRealTime",
  components: { planDialog, mapListModel, BottomNav },
  data() {
    let self = this;
    return {
      polylineList: [],
      treeData: [],
      lineDialogVisible: false,
      setLineVisible: false,
      curLine: {
        lines: []
      },
      streeLightList: [],
      selectStreeLightList: [],

      defaultProps: {
        children: "children",
        label: "label"
      },
      curUnitId: 0,
      unitList: [],
      deviceList: [],
      deviceItem: {
        id: 1,
        name: "line1",
        device: "烟感01",
        line: [[116.43151, 40.098643], [116.459251, 40.098643]]
      },
      droptext: "建筑",
      isSelectMode: true,
      isdelalram: false,
      switchalramtype: "1",
      rowsId: "",
      alarmtype: "1",
      total: null,
      totalStatus: {
        callCount: 0,
        offCount: 0,
        normalCount: 0
      },
      listQuery: {
        page: 1,
        limit: 20,
        alrmCategory: 1
      },
      unhandleItems: [],
      unhandleList: "fireUntreated",
      buildId: "",
      searchAddressKw: "",
      searchAddressList: [],
      queryParams: {
        channelId: ""
      },
      channelId: "",
      cCount: 1,
      realtimePointShow: false,
      markers: [],
      markerRefs: [],
      showTraffic: true,
      showhide: true,
      Trafficlay: undefined, //实时交通图层
      rulerFn: undefined, //测距工具
      ruleroff: true,
      mouseToolOjb: undefined, //鼠标测量工具
      desme: undefined, // 密度计算工具
      localSearch: "1",
      searchOption: {
        city: "武汉",
        citylimit: false
      },
      input5: "",
      isExpand: true,
      buildingList: [],
      selectBuildId: "",
      selectTenant: "",
      list: [],
      tenantlist: [],
      loading: false,
      mapLoad: true,
      states: [],
      center: [114.42377, 30.50469],
      // center: {lng: 0, lat: 0},
      zooms: [5, 19],
      lng: 0,
      lat: 0,
      zoom: 12,
      resized: true,
      vmode: "3D",
      vrotate: 55,
      amapManager,
      clusterobj: undefined,
      events: {
        init: o => {
          o.setMapStyle("amap://styles/117f36d1e643cfd46d21660d866df29e");
          // 点聚合功能
          setTimeout(() => {
            cluster = new AMap.MarkerClusterer(o, self.markerRefs, {
              gridSize: 80,
              minClusterSize: 2,
              maxZoom: 17,
              renderCluserMarker: self._renderCluserMarker
            });
            self.clusterobj = cluster;
            self.mapLoad = false;
          }, 1000);
          let _map = amapManager.getMap();
          _map.on("complete", () => {
            self.getMapCenter();
          });
        }
      },
      plugin: [
        {
          pName: "CitySearch",
          // showMarker:false,
          events: {
            init(o) {
              // o 是高德地图定位插件实例
              // o.getCurrentPosition((status, result) => {
              //   if (result && result.position) {
              //     console.log(result);
              //     self.lng = result.position.lng;
              //     self.lat = result.position.lat;
              //     self.center = [self.lng, self.lat];
              //     self.$nextTick();
              //   }
              // });
              // o.getLocalCity(function (status, result) {
              //   if (status === 'complete' && result.info === 'OK') {
              //     if (result && result.city && result.bounds) {
              //       var cityinfo = result.city;
              //       var citybounds = result.bounds;
              //       let map = amapManager.getMap();
              //       map.setBounds(citybounds);
              //       map.setZoom(12.2)
              //     }
              //   }
              // })
              // o.getCity(function(result){
              //     console.log(result)
              // })
            }
          }
        },
        {
          pName: "Scale",
          events: {}
        }
      ]
    };
  },
  computed: {
    ...mapGetters(["issuperadmin"])
  },
  mounted() {
    this.fetchData();
    //页面高度
    let slmapmainHeight = document
      .querySelector(".sidebar-container")
      .getBoundingClientRect().height;
    // map高度
    let mapHeight = slmapmainHeight;
    document.querySelector("#slmapmain").style.height = mapHeight + "px";
    // 建筑物跟进ws触发更新
    // let ele = this;
    // this.bus.$on("getBuildingStatus", function(val) {
    //   ele.getBuildList(ele.queryParams);
    // });
    this.getUnitList();
  },
  beforeDestroy() {
    this.bus.$off("getBuildingStatus");
  },
  methods: {
    handleLineItem(item) {
      this.curLine = item;
      this.curStreeLightList = item.lines;
      this.selectStreeLightList = item.lines.map(item => item.id);
    },
    addLineItem() {
      this.$prompt("请输路线名", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消"
      })
        .then(({ value }) => {
          const treeItem = this.treeData.find(item => item.lineName === value);
          if (treeItem) {
            this.$message({
              type: "info",
              message: "名字重复请重新输入"
            });
            return false;
          }
          this.$message({
            type: "success",
            message: "增加成功"
          });
          this.treeData.push({
            lineName: value,
            originLineName: value,
            lines: []
          });
        })
        .catch(() => {
          // this.$message({
          //   type: 'info',
          //   message: '取消输入'
          // });
        });
    },
    editLineItem(item) {
      this.$prompt("请输路线名", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        inputValue: item.lineName
      })
        .then(({ value }) => {
          item.lineName = value;
        })
        .catch(() => {
          // this.$message({
          //   type: 'info',
          //   message: '取消输入'
          // });
        });
    },
    deleteLineItem(item) {
      this.$confirm("删除该路线, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          let index = this.treeData.findIndex(
            item1 => item1.lineName === item.lineName
          );
          this.treeData.splice(index, 1);
          console.log("🚀 ~ file: index.vue ~ line 772 ~ .then ~ index", index, this.treeData)

          this.$message({
            type: "success",
            message: "删除成功!"
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除"
          });
        });
    },
    unitChange(val) {
      this.curUnitId = val;
      this.getDeviceList();
    },
    getDeviceList() {
      getFireDeviceByProject({ id: this.curUnitId }).then(res => {
        this.deviceList = res.data;
      });
    },
    getUnitList() {
      getUnitAll("").then(res => {
        this.unitList = res.map(item => {
          return {
            value: item.id,
            label: item.oname
          };
        });
        this.unitChange(this.unitList[0].value);
      });
    },
    drawLines(data) {
      this.markers = []
      const signEnmu = {
        1: '左',
        2: '右',
        3: '停'
      }
      this.polylineList = data.map(item => {
        return item.lines.map(item1 => {
          this.markers.push({
            position: item1.gis.split(","),
            id: item1.id,
            label: "路灯杆",
            status: item1.indicationSign == 3 ? '1': '0',
            count: signEnmu[item1.indicationSign|| 3]
          })
          let arr = item1.gis.split(',')
          return [arr[0], arr[1]]
        })
      })

      let _map = amapManager.getMap();
        _map.setFitView();
    },
    setLines(data) {
      this.lineDialogVisible = true;
      // 默认数据
      if (data.length === 0) {
        data = [
          {
            lineName: "默认",
            lines: []
          }
        ];
      }
      this.treeData = data.map(item => {
        item.originLineName = item.lineName;
        return item;
      });

      this.handleLineItem(data[0]);
      this.$nextTick(() => {
        this.$refs.lineTree.setCurrentKey(data[0].lineName);
      });
    },
    moveUp(item, index) {
      this.curStreeLightList[index] = this.curStreeLightList.splice(
        index - 1,
        1,
        this.curStreeLightList[index]
      )[0];
    },
    moveDown(item, index) {
      this.curStreeLightList[index] = this.curStreeLightList.splice(
        index + 1,
        1,
        this.curStreeLightList[index]
      )[0];
    },
    // 提交修改路线
    subMitLine() {
      this.treeData.forEach(item => {
        const itemData = {
          deviceId: this.curDeviceId,
          lineName: item.lineName,
          originLineName: item.originLineName,
          lineList: item.lines.map(item1 => {
            return {
              terminalScreenNo: item1.terminalScreenNo,
              indicationSign: item1.indicationSign
            };
          })
        };
        updateLineStreeLight(itemData).then(res => {
          console.log(res);
        });
      });

      this.$message.success('修改成功')
      this.lineDialogVisible = false;
    },
    getStreeLightList() {
      this.listLoading = true;
      getDeviceAll().then(res => {
        console.log("this.streeLightList-res", res);
        this.streeLightList = res.map((item, index) => {
          return {
            label: "路灯杆" + item.id,
            sort: index,
            ...item
          };
        });
        console.log("this.streeLightList", this.streeLightList);
        this.listLoading = false;
      });
    },
    setStreeLightList() {
      const curStreeLightList = this.streeLightList.filter(item =>
        this.selectStreeLightList.includes(item.id)
      );
      console.log(
        "🚀 ~ file: index.vue ~ line 892 ~ setStreeLightList ~ curStreeLightList",
        curStreeLightList
      );

      this.curLine.lines = curStreeLightList
      // 默认左转
      this.curLine.lines.forEach(item => {
        if (!item.indicationSign) {
          this.$set(item, "indicationSign", "1"); 
        }
      });
    },
    handleSure() {
      if (this.alarmtype == 1) {
        //火警
        changeFireRsolve(
          this.$qs.stringify({ id: this.rowsId, flag: this.switchalramtype })
        )
          .then(res => {
            if (res.status === 200) {
              this.$notify({
                title: "成功",
                message: "处理成功",
                type: "success",
                duration: 2000
              });
              this.isdelalram = false;
              this.switchalramtype = "1";
              this.getUnhandleL();
            }
          })
          .catch(res => {
            this.$notify({
              title: "提示",
              message: "网络异常！",
              type: "warning",
              duration: 2000
            });
            this.isdelalram = false;
          });
      } else {
        //故障
        changeRsolve(this.$qs.stringify({ id: this.rowsId }))
          .then(res => {
            if (res.status === 200) {
              this.$notify({
                title: "成功",
                message: "处理成功",
                type: "success",
                duration: 2000
              });
              this.isdelalram = false;
              this.getUnhandleL();
            }
          })
          .catch(res => {
            this.$notify({
              title: "提示",
              message: "网络异常！",
              type: "warning",
              duration: 2000
            });
            this.isdelalram = false;
          });
      }
    },
    handleCurrentChange(val) {
      //  简版翻页
      this.listQuery.page = val;
      this.getUnhandleL();
    },
    changeMode(type) {
      //this.isExpand=false;
      this.unhandleList = "fireUntreated";
      switch (type) {
        case "map":
          this.isSelectMode = true;
          this.isExpand = true;
          getAllStatus(this.queryParams).then(res => {
            this.totalStatus = res.data;
          });
          this.getUnhandleL();
          break;
        case "list":
          this.isSelectMode = false;
          this.isExpand = false;
          break;
      }
    },
    fetchData() {
      //修复高德地图加载的bug
      if (localStorage.getItem("logined")) {
        let addStorage = localStorage.getItem("logined");
        this.clearMapstore();
        localStorage.setItem("logined", addStorage);
      } else {
        this.clearMapstore();
      }
      this.channelId = this.$route.params.id;
      this.queryParams.channelId = this.$route.params.id;
      this.getBuildList(this.queryParams);
      this.isExpand = true;
      this.changeMode("map");
      if (this.issuperadmin) {
        this.getAllTenant();
      }
    },
    getBuildList(query) {
    },
    changeIt() {
      this.isExpand = !this.isExpand;
      // 展开列表请求
      if (this.isExpand) {
        getAllStatus(this.queryParams).then(res => {
          this.totalStatus = res.data;
        });
        this.getUnhandleL();
      }
    },
    getUnhandleL() {
      // 加载未处理列表
      this.loading = true;
      getUnhandleList(Object.assign(this.listQuery, this.queryParams)).then(
        res => {
          this.loading = false;
          this.total = res.data.total;
          this.unhandleItems = res.data.rows;
        }
      );
    },
    showSensor(val) {
      this.buildId = val + "";
      this.realtimePointShow = true;
      document.querySelector(".propper-class").style.display = "none";
      document.querySelector(".tenant-propper-class").style.display = "none";
    },
    selectedAddress(item) {
      let lnglat = item.location;
      let self = this;
      if (lnglat) {
        this.center = [lnglat.lng, lnglat.lat];
      } else {
        let o = amapManager.getMap();
        o.setCity(item.name, function() {
          self.zoom = 12;
        });
      }
      // 关闭测距
      if (this.rulerFn) {
        this.rulerFn.turnOff();
      }
      this.zoom = 19;
    },
    remoteMethod(pois) {
      let self = this;
      // 选择之后的列表
      AMap.plugin(["AMap.Autocomplete"], function() {
        var autoOptions = {
          city: "" // 城市，默认全国
        };
        var autoComplete = new AMap.Autocomplete(autoOptions);
        autoComplete.search(pois, function(status, result) {
          // 搜索成功时，result即是对应的匹配数据
          if (result) {
            let results = result.tips;
            if (results) {
              self.searchAddressList = results;
            }
          }
        });
      });
    },
    selectHandle(command) {
      this.localSearch = command;
      if (command === "1") {
        this.droptext = "建筑";
      } else if (command === "2") {
        this.droptext = "地名";
      } else {
        this.droptext = "站点";
      }
    },
    handleCommand(command) {
      if (command === "showtrafic") {
        if (this.showTraffic) {
          let o = amapManager.getMap();
          let trafficLayer = new AMap.TileLayer.Traffic();
          trafficLayer.setMap(o);
          this.Trafficlay = trafficLayer;
          this.showTraffic = false;
        } else {
          // 非第一次显示路况
          if (this.showhide) {
            this.Trafficlay.hide();
            this.showhide = false;
          } else {
            this.Trafficlay.show();
            this.showhide = true;
          }
        }
      } else if (command === "showpich") {
        let self = this;
        if (this.ruleroff) {
          // 显示测距工具
          let o = amapManager.getMap();

          o.plugin(["AMap.RangingTool"], function() {
            let ruler = new AMap.RangingTool(o);

            ruler.turnOn();

            self.$nextTick();

            self.rulerFn = ruler;
            self.ruleroff = false;
          });
        } else {
          self.rulerFn.turnOff();
          self.ruleroff = true;
        }
      } else if (command === "showDensity") {
        let self = this;

        let o = amapManager.getMap();
        if (!this.desme) {
          o.plugin(["AMap.MouseTool"], function() {
            let mouseTool = new AMap.MouseTool(o);
            self.desme = mouseTool;
            //鼠标工具插件添加draw事件监听
            AMap.event.addListener(mouseTool, "draw", function callback(e) {
              var eObject = e.obj; //obj属性就是鼠标事件完成所绘制的覆盖物对象。

              var polygon = new AMap.Polygon({
                path: eObject.getPath(),
                extData: "99"
              });

              let num = 0;
              // let allShowDevices = self.markers;
              // for (let i = 0; i < allShowDevices.length; i++) {
              //   let position = allShowDevices[i].position;
              //   let count = allShowDevices[i].count;
              //   if (polygon.contains(position) == true)
              //     // 目前是建筑物传感器数量
              //     num += count;
              // }

              let size = (polygon.getArea() / 1000000).toFixed(2);
              //let info = `面积:  ${size} 平方公里，数量为:  ${num} 栋`;
              let info;
              if (num > 0)
                info = "密度为：" + (num / size).toPrecision(4) + "个/平方公里";
              else info = "无传感器";
              setTimeout(() => {
                document
                  .querySelectorAll(".amap-marker-content>div")
                  .forEach(item => {
                    if (item.children.length < 1) {
                      if (!item.getAttribute("id")) {
                        item.setAttribute("id", "amcM-" + self.cCount++);
                        item.innerText = info;
                      }
                    }
                  });
              }, 200);
            });
            mouseTool.measureArea(); //调用鼠标工具的面积量测功能
          });
        } else {
          window.location.reload();
        }
      }
    },
    unitQuerySearch() {},
    querySearch(queryString, cb) {
      if (queryString == "") {
        cb([]);
      } else {
        getBuildingList(
          Object.assign({}, this.queryParams, { bName: queryString })
        ).then(res => {
          var buildings = res.data;
          if (buildings.length == 0) {
            cb([]);
          } else {
            let buildarr = [];
            buildings.forEach(build => {
              buildarr.push({ value: build.name, id: build.id });
              cb(buildarr);
            });
          }
        });
      }
    },
    getAllTenant() {
      getAllTenant(this.queryParams).then(res => {
        var buildings = res.data.rows;
        if (buildings.length == 0) {
          this.tenantlist = [];
        } else {
          let buildarr = [];
          buildings.forEach(build => {
            buildarr.push({ value: build.name, id: build.id });
            this.tenantlist = buildarr;
          });
        }
      });
    },
    createFilter(queryString) {
      return restaurant => {
        return (
          restaurant.value.toLowerCase().indexOf(queryString.toLowerCase()) ===
          0
        );
      };
    },
    tenantSearch(queryString, cb) {
      var restaurants = this.tenantlist;
      if (queryString == "") {
        if (cluster) {
          cluster.setMap(null);
        }
        this.getBuildList(this.queryParams);
        this.mapcluster();
        /*this.getBuildList(this.queryParams);
          this.mapcluster();*/
        var results = restaurants.filter(this.createFilter(queryString));
        cb(results);
      } else {
        var results = restaurants.filter(this.createFilter(queryString));
        if (results.length == 0) {
          this.$message({
            message: "站点中未添加建筑",
            type: "warning"
          });
        }
        cb(results);
      }
    },
    freshCenter(pos) {
      this.center = [pos.gisx, pos.gisy];
      this.zoom = 19;
      // 关闭测距
      if (this.rulerFn) {
        this.rulerFn.turnOff();
      }
    },
    handleSelect(build) {
      let selectedBuild = this.states.find(item => {
        return item.id === build.id;
      });
      if (selectedBuild) {
        this.freshCenter(selectedBuild);
      }
    },
    mapcluster() {
      let self = this;
      let map = amapManager.getMap();
      setTimeout(function() {
        map.plugin("AMap.MarkerClusterer", function() {
          cluster = new AMap.MarkerClusterer(map, self.markerRefs, {
            gridSize: 80,
            minClusterSize: 3,
            renderCluserMarker: self._renderCluserMarker
          });
        });
        if (cluster.length > 0) cluster.setMarkers(self.markers);
      }, 0);
    },
    handleSelecttenant(val) {
      let self = this;
      self.markerRefs.length = 0;
      if (cluster) {
        cluster.setMap(null);
      }
      self.markers.length = 0;
      getTenantPos({ tenantId: val.id }).then(res => {
        let markers = res.data;
        let markarr = [];
        for (let i = 0; i < markers.length; i++) {
          self.markers.push({
            position: [markers[i].gisx, markers[i].gisy],
            id: markers[i].id,
            label: markers[i].name,
            status: markers[i].status,
            count: markers[i].count,
            events: {
              init(o) {
                self.markerRefs.push(o);
              }
            }
          });
        }
        this.mapcluster();
      });
    },
    getMapCenter() {
      getMaxAlarm(this.queryParams).then(res => {
        this.center = res.data.gis.split(",");
      });
    },
    _renderCluserMarker(context) {
      // 点聚合方法
      const count = this.markers.length;

      let factor = Math.pow(context.count / count, 1 / 18);
      let div = document.createElement("div");
      let Hue = 180 - factor * 180;
      // let bgColor = 'hsla('+Hue+',100%,50%,0.7)';
      // let fontColor = 'hsla('+Hue+',100%,20%,1)';
      // let borderColor = 'hsla('+Hue+',100%,40%,1)';
      // let shadowColor = 'hsla('+Hue+',100%,50%,1)';
      let bgColor = "hsla(153,100%,33%,0.7)";
      let fontColor = "hsla(0,0%,100%,1)";
      let borderColor = "hsla(153,100%,40%,1)";
      let shadowColor = "hsla(" + Hue + ",100%,50%,1)";
      div.style.backgroundColor = bgColor;
      let size = Math.round(30 + Math.pow(context.count / count, 1 / 5) * 20);
      div.style.width = div.style.height = size + "px";
      div.style.border = "solid 1px " + borderColor;
      div.style.borderRadius = size / 2 + "px";
      div.style.boxShadow = "0 0 1px " + shadowColor;
      div.innerHTML = context.count;
      div.style.lineHeight = size + "px";
      div.style.color = fontColor;
      div.style.fontSize = "14px";
      div.style.textAlign = "center";
      context.marker.setOffset(new AMap.Pixel(-size / 2, -size / 2));
      context.marker.setContent(div);
    },
    handleCopy(text, event) {
      clip(text + "", event);
    },
    checkMore() {
      let rootPath = this.$route.matched[0];
      if (rootPath.path === "") {
        this.$router.push("/gailan/exceptionRecord");
      } else {
        // 加载更多修改
        let lastPath =
          this.queryParams.channelId !== undefined
            ? "/" + this.queryParams.channelId
            : "";
        this.$router.push(rootPath.path + "/exceptionRecord" + lastPath);
      }
    },
    initPage() {
      this.listQuery.page = 1;
      this.listQuery.limit = 20;
    },
    unhandleChange() {
      // 火警列表和故障列表切换
      this.unhandleItems = [];
      if (this.unhandleList === "fireUntreated") {
        this.initPage();
        this.listQuery.alrmCategory = 1;
        this.getUnhandleL();
        this.alarmtype = 1;
      } else {
        this.initPage();
        this.listQuery.alrmCategory = 0;
        this.getUnhandleL();
        this.alarmtype = 0;
      }
    },
    // 设置定位到地图
    handleRows(row, type) {
      this.curDeviceId = row.id;
      getLinesByDeviceId({ deviceId: row.id }).then(res => {
        console.log("rowres", res);
        // 去设置
        if (type === "set") {
          this.setLines(res.data);
          return;
        }
        // 去展示
        if (res.data.length) {
          this.drawLines(res.data);
        } else {
          this.$confirm("当前设备没有设置路线，是否设置?", "提示", {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning"
          })
            .then(() => {
              // 去设置
              this.setLines([]);
            })
            .catch(() => {
              this.$message({
                type: "info",
                message: "已取消删除"
              });
            });
        }
      });
    }
  },
  watch: {
    $route: "fetchData"
  }
};
</script>
<style rel="stylesheet/scss" lang="scss" scoped>
.add-line-top {
  display: flex;
  justify-content: flex-end;
  margin: -60px 0 10px;
}

.set-line-block {
  width: 100%;
  display: flex;
  justify-content: space-around;

  .left-warp {
    width: 220px;
    margin-right: 20px;
  }

  .right-warp {
    width: calc(100% - 240px);
  }

  .line-title {
    padding: 10px;
    font-size: 14px;
    font-weight: 600;
  }
}

.tool-wrap .tool-wrap-items .map-listchange__mode,
.tool-wrap .tool-wrap-items .map-tool-item,
.tool-wrap .tool-wrap-items .map-dotshow-wrap {
  padding: 0 12px;
}
.tool-wrap {
  top: 20px;
}
.loadmore-btn-goto {
  text-align: center;
}
.map-mode-pannel,
.list-mode-pannel,
.untreated-list {
  .el-scrollbar__wrap {
    overflow-x: hidden;
  }
}
.dropdwon-svg-icon {
  margin-right: 10px;
}
.amap-geolocation-con {
  left: auto !important;
  right: 30px;
  bottom: 107px !important;
  z-index: auto !important;
}
.amap-ui-control-zoom {
  width: 35px !important;
}
#slmapmain {
  overflow: hidden;
  position: relative;
  .map-mode-pannel {
    display: none;
    height: 100%;
    &.map-pannel-show {
      display: block;
    }
  }
  .list-mode-pannel {
    width: 100%;
    height: 100%;
    display: none;
    &.list-pannel-show {
      display: block;
      .tool-wrap {
        right: 350px;
      }
    }
  }
}

.border_message {
  width: 100%;
  display: flex;
  justify-content: space-between;
  flex-wrap: wrap;
  padding: 20px;
  .border_message_num {
    width: 180px;
    height: 87px;
  }
}

.list-warp {
  margin-top: 20px;
  height: 520px;
}

.mapset {
  height: 100%;
  .amap-logo {
    display: none !important;
  }
  .amap-copyright {
    visibility: hidden !important;
  }
  .amap-ui-control-position-rb {
    background: #fff;
  }
  .map-marker-wrapn {
    .bubble {
      margin-top: -75px;
      margin-left: -6px;

      left: 50%;
      transform: translateX(-50%);
      position: absolute;
      .build-name {
        display: inline-block;
        white-space: nowrap;
        font-style: normal;
        color: #fff;
        padding: 5px 10px;
        background-color: #4ab7bd;
        border-radius: 2px;
        border: 1px solid #4ab7bd;
        min-width: 40px;
        font-size: 12px;
      }
      .arrow-up {
        border: 4px solid transparent;
        border-top-width: 4px;
        border-top-color: #4ab7bd;
        display: block;
        width: 0;
        height: 0;
        margin: 0 auto;
      }
    }
    .main-map-markern {
      display: inline-block;
      margin-left: -13px;
      width: 44px;
      height: 44px;
      color: transparent;
      font-size: 14px;
      text-align: center;
      line-height: 28px !important;
      position: relative;
      &.main-map-marker__notify {
        background: url("~@/assets/default-images/warning.png") no-repeat;
        background-size: cover !important;
        color: #fff;
      }
      &.main-map-marker__normaln {
        background: url("~@/assets/default-images/normal.png") no-repeat;
        background-size: cover !important;
        color: #fff;
      }
    }
  }
}

.search-select {
  /deep/ .el-input {
    .el-input__inner {
      border-radius: 0;
      background-color: #162857;
      height: 21px;
      line-height: 21px;
    }
    .el-input__suffix {
      top: -7px;
    }
  }
}

.custom-tree-node {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: space-between;
  font-size: 14px;
  padding-right: 8px;
}
</style>
